<template>
  <el-dialog
    v-model="visibility"
    width="60%"
    :title="props.rowData.id ? config.button.text.edit : config.button.text.add"
    append-to-body
    draggable
    :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="config.form.label.width"
      status-icon>
      <el-row>
        <el-col
          :span="appStore.isPhone?24:12"
          class="el_col_fit">
          <el-form-item
            label="主体公司简称"
            prop="baseCompanyId">
            <el-select
              v-model="formData.baseCompanyId"
              placeholder="主体公司简称"
              filterable
              clearable>
              <el-option
                v-for="item in mainOrgSimplyOptions"
                :key="item.id"
                :disabled="item.disabled"
                :label="item.simple_name"
                :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="appStore.isPhone?24:12"
          class="el_col_fit">
          <el-form-item
            label="资金方简称"
            prop="baseCapitalPartyId">
            <el-select
              v-model="formData.baseCapitalPartyId"
              placeholder="资金方简称"
              filterable
              clearable>
              <el-option
                v-for="item in fundingOptions"
                :key="item.id"
                :disabled="item.disabled"
                :label="item.simple_name"
                :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="appStore.isPhone?24:12"
          class="el_col_fit">
          <el-form-item
            label="仓库名称"
            prop="baseCapitalPartyId">
            <el-select
              v-model="formData.baseWarehouseId"
              placeholder="仓库名称"
              filterable
              clearable>
              <el-option
                v-for="item in baseWarehouseOptions"
                :key="item.id"
                :disabled="item.disabled"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="appStore.isPhone?24:12"
          class="el_col_fit">
          <el-form-item
            label="资金仓库名称"
            prop="name">
            <el-input
              v-model="formData.name"
              clearable
              placeholder="资金仓库名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="appStore.isPhone?24:12"
          class="el_col_fit">
          <el-form-item
            label="启用状态"
            prop="isEnable">
            <el-select
              v-model="formData.isEnable"
              placeholder="启用状态"
              clearable>
              <el-option
                :label="config.button.text.enable"
                :value="true" />
              <el-option
                :label="config.button.text.stop"
                :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="appStore.isPhone?24:12"
          class="el_col_fit">
          <el-form-item
            label="日化率(%)"
            prop="dailyChemicalRate">
            <el-input-number
              v-model="formData.dailyChemicalRate"
              :min="0"
              :max="100"
              :precision="4"
              controls-position="right"
              placeholder="日化率" />
          </el-form-item>
        </el-col>
        <el-col :span="appStore.isPhone?24:12">
          <el-form-item
            label="我司预付款百分比(%)"
            prop="companyFirstPayPercent">
            <el-input-number
              v-model="formData.companyFirstPayPercent"
              :min="0"
              :max="100"
              :precision="2"
              controls-position="right"
              placeholder="我司预付款百分比" />
          </el-form-item>
        </el-col>
        <el-col :span="appStore.isPhone?24:12">
          <el-form-item
            label="资方预付款百分比(%)"
            prop="capitalFirstPayPercent">
            <el-input-number
              v-model="formData.capitalFirstPayPercent"
              :min="0"
              :max="100"
              :precision="2"
              controls-position="right"
              placeholder="资方预付款百分比" />
          </el-form-item>
        </el-col>
        <el-col :span="appStore.isPhone?24:12">
          <el-form-item
            label="资方尾款百分比(%)"
            prop="capitalEndPayPercent">
            <el-input-number
              v-model="formData.capitalEndPayPercent"
              :min="0"
              :max="100"
              :precision="2"
              controls-position="right"
              placeholder="资方尾款百分比" />
          </el-form-item>
        </el-col>
        <el-col
          :span="24"
          class="el_col_fit">
          <el-form-item
            label="备注"
            prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              :autosize="{ minRows: 2, maxRows: 4 }"
              clearable
              placeholder="备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="table-title">仓储费列表：</div>
              <div class="header-btn">
                <el-button
                  type="info"
                  @click="addBaseWarehouseOption">
                  {{ config.button.text.add }}
                </el-button>
              </div>
            </template>
            <el-table
              v-if="!appStore.isPhone"
              max-height="200px"
              :data="tableData"
              style="width: 100%"
              border="1">
              <el-table-column
                prop="name"
                label="仓储费名称"
                :resizable="false" />
              <el-table-column
                prop="storageChargeFee"
                label="仓储费（元/吨）"
                :resizable="false" />
              <el-table-column
                prop="isTimeSection"
                label="是否按照时间段"
                :resizable="false">
                <template #default="scope">
                  <span>{{ scope.row.isTimeSection ? '是' : '否' }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="300"
                :resizable="false">
                <template #default="{ row }">
                  <el-button
                    type="warning"
                    @click="handleEdit(row)">
                    {{ config.button.text.edit }}
                  </el-button>
                  <el-button
                    type="success"
                    @click="handleView(row)">
                    查看时间段分段列表
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-card
              v-else
              class="table_card info-card"
              v-for="item in tableData"
              :key="item.id"
              @click="handleView(item)">
              <div class="info-item">
                <div class="info-title">仓储费名称：</div>
                <div class="info-main">{{ item.name }}</div>
              </div>
              <div class="info-item">
                <div class="info-title">仓储费（元/吨）：</div>
                <div class="info-main">{{ item.storageChargeFee }}</div>
              </div>
              <div class="info-item">
                <div class="info-title">是否按照时间段：</div>
                <div class="info-main">{{ item.isTimeSection ? '是' : '否' }}</div>
              </div>
            </el-card>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
        <el-button
          type="primary"
          @click="saveEvent">
          {{ config.button.text.save }}
        </el-button>
      </div>
    </template>
    <!-- 仓储费新增修改 -->
    <sonEdit
      ref="sonEditRef"
      :sonRowData="sonRowData"
      @son-save="sonSave" />
    <!-- 仓储费查看 -->
    <sonView
      ref="sonViewRef"
      @edit-info="handleEdit"
      :sonRowData="sonRowData" />
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import config from "@/common/element-plus/config";
import { useValidator } from "@/hooks/useValidator";
import ApiBaseCapitalWarehouse from "@/api/modules/capital-ware-house"
import sonEdit from "./sonEdit.vue"
import sonView from "./sonView.vue"
import message from "@/common/element-plus/message";
import { useAppStore } from "@/stores/app"

const visibility = ref(false)
const formData = ref({})
const formRef = ref()
const { required, validate, clearValidate } = useValidator()
//主体公司简称列表
const mainOrgSimplyOptions = ref([]);
//资金方简称列表
const fundingOptions = ref([]);
//仓库简称列表
const baseWarehouseOptions = ref([]);
const props = defineProps(["rowData"])
const sonRowData = ref({})

//仓储费列表
const tableData = ref([]);
//仓储费列表实例
const sonEditRef = ref()
const sonViewRef = ref()

const formRules = {
  baseCompanyId: [required("主体公司简称")],
  baseCapitalPartyId: [required("资金方简称")],
  baseWarehouseId: [required("仓库简称")],
  name: [required("资金仓库名称")],
  dailyChemicalRate: [required("日化率")],
  companyFirstPayPercent: [required("我司预付款百分比")],
  capitalFirstPayPercent: [required("资方预付款百分比")],
  capitalEndPayPercent: [required("资方尾款百分比")],
  isEnable: [required("启用状态")]
}

const emits = defineEmits(["save"]);

watch(() => visibility.value, (newVal) => {
  if (newVal) {
    if (!props.rowData.id) {
      formData.value = {
        ...props.rowData,
        isEnable: true,
      };
    } else {
      formData.value = { ...props.rowData };
    };
    getMainOrgList();
    getBaseCapitalPartyOption();
    getBaseWarehouseOption();
    getStorageChargeList(formData?.value?.id || "");
    editIndex.value = -1;
    setTimeout(() => {
      clearValidate(formRef.value)
    })
  }
}, { immediate: true })

//保存
const saveEvent = async () => {
  await validate(formRef.value)
  if (formData.value.id) {
    await ApiBaseCapitalWarehouse.update(formData.value)
  } else {
    await ApiBaseCapitalWarehouse.insert(formData.value)
  }
  emits("save")
}

//获取仓储费列表
const getStorageChargeList = async (id) => {
  if (id) {
    const res = await ApiBaseCapitalWarehouse.getStorageChargeList({ baseCapitalWarehouseId: id }, {
      pageNum: 1,
      pageSize: -1,
    });
    tableData.value = res.data.records;
  } else {
    tableData.value = [];
  }
}

//获取主体公司简称列表
const getMainOrgList = async () => {
  const orgObj = {
    id:formData.value.baseCompanyId,
    simple_name:formData.value.baseCompanySimpleName,
    disabled:true
  }
  const res = await ApiBaseCapitalWarehouse.getSimpleNameList("/baseCompany/");
  if (res?.code == 200 && Array.isArray(res?.data) && res?.data.length > 0) {
    mainOrgSimplyOptions.value = res.data;
    const findItem = res.data.find(item=>item.id===orgObj.id);
    if(!findItem&&props.rowData.id){
      orgObj.simple_name+='(已禁用)'
      mainOrgSimplyOptions.value.push(orgObj);
    }
  }
}

//获取资金方简称列表
const getBaseCapitalPartyOption = async () => {
  const orgObj = {
    id:formData.value.baseCapitalPartyId,
    simple_name:formData.value.baseCapitalPartySimpleName,
    disabled:true
  }
  const res = await ApiBaseCapitalWarehouse.getSimpleNameList("/baseCapitalParty/");
  if (res?.code == 200 && Array.isArray(res?.data) && res?.data.length > 0) {
    fundingOptions.value = res.data;
    const findItem = res.data.find(item=>item.id===orgObj.id);
    if(!findItem&&props.rowData.id){
      orgObj.simple_name+='(已禁用)'
      fundingOptions.value.push(orgObj);
    }
  }
}

//获取仓库简称列表
const getBaseWarehouseOption = async () => {
  const orgObj = {
    id:formData.value.baseWarehouseId,
    simple_name:formData.value.baseWarehouseName,
    disabled:true
  }
  const res = await ApiBaseCapitalWarehouse.getSimpleNameList("/baseWarehouse/");
  if (res?.code == 200 && Array.isArray(res?.data) && res?.data.length > 0) {
    baseWarehouseOptions.value = res.data;
    const findItem = res.data.find(item=>item.id===orgObj.id);
    if(!findItem&&props.rowData.id){
      orgObj.simple_name+='(已禁用)'
      baseWarehouseOptions.value.push(orgObj);
    }
  }
}
/************ 仓储费列表 ************/
//表格可编辑
const editIndex = ref(-1)

const handleEdit = (row) => {
  sonEditRef.value.visibility = true
  sonRowData.value = Object.assign({}, row)
}

const handleView = (row) => {
  sonViewRef.value.visibility = true
  sonRowData.value = {...row,showEdit: true}
}
const appStore = useAppStore()

//新增仓库费
const addBaseWarehouseOption = () => {
  sonEditRef.value.visibility = true
  sonRowData.value = { baseCapitalWarehouseId: formData.value.id }
}

// 仓储费保存后回调
const sonSave = async (obj) => {
  if (obj) {
    if (obj?.index !== null && obj?.index !== undefined) {
      tableData.value[obj?.index] = obj;
    } else {
      obj.index = tableData.value.length
      tableData.value.push(obj);
    }
    formData.value.baseCapitalWarehouseCostRule = tableData.value
  } else {
    await getStorageChargeList(formData.value.id);
  }
  sonEditRef.value.visibility = false
  message.success()
}

defineExpose({ visibility })


</script>

<style lang="scss" scoped>
.el-row {
  align-items: flex-start;
}

:deep(.el-form-item__label) {
  width: 160px !important;
}

.table-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.el-input-number {
  width: 100%;
}

:deep(.el-card__header) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}

.info-card {
  // padding: 10px;
  margin-bottom: 3px;
  .info-item {
    display: flex;
    padding: 5px 0;
    align-items: end;
    .info-title{
      width: 120px;
      color: #999;
    }
    .info-main{
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

@media screen and (max-width: 700px) {
  :deep(.el-form-item__label) {
    width: 110px !important;
  }
}
</style>
